import CryptoJS from 'crypto-js';

const base64ToStr = (library) => {
	const str = CryptoJS.enc.Base64.parse(library).toString(CryptoJS.enc.Utf8);
	return str;
};

//生成指定key  offset偏移量
const generatekey = (offset) => {
	const library = 'SFVvYVN0Uk9kZXZ3ZlZJMUtzTUNqR2lReDByY21ieVhnaE5rQkxGNVdUN3VEbnpQWTY0cDkyQTNKbHFFWjg='
	const lis = base64ToStr(library)
	const keyNum = 'NTh8N3wyOXwzMXw0NnwtMnwyN3w0NHwxNXw0NXw1OA=='
	const keyVal = base64ToStr(keyNum)
	let key = ''
	keyVal.split('|').forEach((num) => {
		key = key + lis[Number(num) + offset]
	})
	return key
}

//DES加密8vgN6UyPMY8
//DES加密8vgN6UyPMY8

export function encryptByDES(message) {
	const key = generatekey(3);

	var keyHex = CryptoJS.enc.Utf8.parse(key);

	var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7,
	});
	return encrypted.toString();
}

//DES解密
export function decryptByDES(ciphertext, type) {
	const key = generatekey(3);
	var keyHex = CryptoJS.enc.Utf8.parse(key);
	var decrypted = CryptoJS.DES.decrypt({
			ciphertext: CryptoJS.enc.Base64.parse(ciphertext),
		},
		keyHex, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7,
		}
	);

	const decVal = decrypted.toString(CryptoJS.enc.Utf8)
	if (type === 'phone') {
		const phone = decVal.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
		return phone
	}
	if (type === 'idCard') {
		const idCard = decVal.replace(/(\d{3})\d{11}(\d{4})/, '$1***********$2')
		return idCard
	}

	return decVal
}